<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template> -->
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <!-- v-if="hasPointsPermission('excel_import')" -->
          <el-button v-permission="'excel_import'" type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <!-- v-if="hasPointsPermission('excel_export')" -->
          <el-button v-permission="'excel_export'" type="danger" size="small" @click="excelImport">excel导出</el-button>
          <!-- v-if="hasPointsPermission('p-em-add')" -->
          <el-button v-permission="'p-em-add'" type="primary" size="small" @click="addEmployeesFn">新增员工</el-button>
        </template>
      </PageTools>

      <el-card v-loading="isLoading" style="margin-top: 10px">
        <el-table border :data="employeeList">
          <el-table-column label="序号" type="index" width="80px" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img v-imgerror="defaultImg" class="staff" :src="row.staffPhoto||nullImage">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formateData" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ formateTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <!-- v-if="hasPointsPermission('p-em-look')" -->
              <el-button v-permission="'p-em-look'" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <!-- v-if="hasPointsPermission('assign_role')" -->
              <el-button v-permission="'assign_role'" type="text" size="small" @click="assignRole(row.id)">分配角色</el-button>
              <!-- v-if="hasPointsPermission('emp_delete')" -->
              <el-button v-permission="'emp_delete'" type="text" size="small" @click="handleDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total,sizes,prev, pager, next,jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <add-employee :show-dialog.sync="showDialog" />
      </el-card>
      <assignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import AssignRole from './components/assign-role.vue'
import { getEmployeesListApi, delEmployeesApi } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import dayjs from 'dayjs'
import AddEmployee from './components/add-employee.vue'
// import { mapGetters } from 'vuex'
// 使用mixins的方式  1.先导入mixins所在的文件 2.把mixins混入当前组件中(mixins: [index])
import permission from '@/mixins/permission'

export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  mixins: [permission],
  data() {
    return {
      page: 1,
      size: 0,
      employeeList: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      defaultImg: 'avatar',
      nullImage: 'http://hrsass-151-xy-1315205683.cos.ap-beijing.myqcloud.com/16690815326962.gif',
      showRoleDialog: false,
      userId: ''
    }
  },
  // 在mixins中有导入
  // computed: {
  //   ...mapGetters(['roles'])
  // },
  created() {
    this.getEmployeesList()
  },
  methods: {
    // 按钮功能  mixins 中有使用
    // hasPointsPermission(points) {
    //   return this.roles?.points?.includes(points)
    // },
    // 分配角色
    assignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    // 导入
    async excelImport() {
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const { data: { rows }} = await getEmployeesListApi(1, this.total)
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const data = this.formateData2Arrar(headersArr, rows, headersRelations)
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // excel 表头
          // 导出的数据必须是二维数组
          data: data, // excel中的数据 （必填）
          filename: '信息导出', // 导出文件的文件名（非必填项）
          autoWidth: true, // 单元格宽度是否自适应（非必填项）
          bookType: 'xlsx' // 文件后缀名（非必填项）
        })
        this.downloadLoading = false
      })
    },
    // 二维数据
    formateData2Arrar(headersArr, rows, headersRelations) {
      const arr = []
      rows.forEach(item => {
        const tempArray = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            const hireObj = EmployeeEnum.hireType.find(item => item.id === Number(value)
            )
            value = hireObj ? hireObj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = value ? this.formatTime(value) : ''
          }
          tempArray.push(value)
        })
        arr.push(tempArray)
      })
      return arr
    },
    async getEmployeesList() {
      this.isLoading = true
      const { data } = await getEmployeesListApi(this.page, this.size)
      this.employeeList = data.rows
      this.total = data.total
      this.isLoading = false
    },
    /**
     * 页容量改变
     */
    handleSizeChange(val) {
      this.size = val
      this.getEmployeesList()
    },
    /**
     * 页码改变
     */
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeesList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    /**
     * 聘用形式
     */
    formateData(row, column, cellValue, index) {
      // console.log(cellValue)
      // 正式 id=1  非正式 id2 临时工 钟点工 清洁工 实习生
      // if (cellValue === 1) {
      //   return '正式'
      // }
      // if (cellValue === 2) {
      //   return '非正式'
      // }
      const hireObj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      // console.log(hireObj)
      return hireObj ? hireObj.value : '未知'
    },
    /**
     * 入职时间
     */
    formateTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    /**
     * 删除员工
     */
    handleDel(id) {
      this.$confirm('是否确定删除', '温馨提示').then(
        async() => {
          await delEmployeesApi(id)
          if (this.employeeList.length === 1 && this.page > 1) {
            this.page--
          }
          this.$message.success('删除成功')
          this.getEmployeesList()
        }
      ).catch()
    },
    /**
     * 新增员工
     */
    addEmployeesFn() {
      this.showDialog = true
    }
  }

}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}

</style>
